
var CONFIG = (function() {
	
	//var url = window.ajaxUrl;
	//console.log(window.ajaxUrl);
		
	var private = {
			'AJAX_URL':					window.ajaxUrl,	
			'CREATE_RESERVATION':		this.AJAX_URL + '\createReservationAction',
			'CONST2':		2
	};
	
	return {
		get: function(name) { return private[name]; }
	};
		
})();
	

$(document).ready(function() {
	
	loadExtras();
	offerListEvents();
	extrasListEvents();
	formFocusEvents();
	formConf();
	datatablePlugins();
	datatableClient();
	buttonEvents();
	tmp();
});


function tmp() {
	//console.log(CONFIG.get('AJAX_URL'));
	//console.log(CONFIG.get('CREATE_RESERVATION'));
	//CONFIG.get('CONST1')
}


/**
 * function to retrieve data from the server
 * @param params - data to be sent
 * @param method - the method to make the request
 * @returns - data returned from the server
 */
function getDataFromSrv(params, method) {
	
	var data = null;
	
	var opt = {
		url: 		window.ajaxUrl + method,
		async: 		false, // ... wait to retrieve the data from the server
		data: 		{ data: params },
		type: 		'POST',
		dataType: 	'json',
		success: 	function(serverData) {
			data = serverData;
		}
	};
	
	$.ajax(opt);
	
	return data;
}


/**
 * Show a jqueyUI dialog
 * @param title
 * @param content
 * @param width
 * @param height
 */
function showAlert(title, content, width, height) {
	
	var genericAlert = $('#genericAlert');
	
	var options = {
		width:		width,
		height:		height,
		show: 		'fade',
		hide: 		'fade',
		buttons: {
			"Ok": 		
			function() {
				$(this).dialog("close");
			},
			"Cancel": 		
			function() {
				$(this).dialog("close");
			}
		}
	};
	
	genericAlert.attr('title',title).html(content).dialog(options);
}


/**
 * Actions when reserve button is pressed
 */
function reserveButtonAction() {
	
		// empty array
		var extras 		= [];
		
		//var transport 	= 'no';
	
		var clientForm = $('#clientForm');
	
		var clientId = clientForm.attr('data-id');
		
		var offer_id = $('input[name=offerRadio]:checked').parents().eq(1).find('a').attr('data-offerId');
		
		if (!offer_id) {
			showAlert('erro','Não existem ofertas disponiveis', 350, 150);
			return;
		}
		
		var class_id = $('input[name=offerRadio]:checked').parents().eq(1).find('a').attr('data-classId');
		
		if (parseInt(clientId)) { // ... a client is selected
			
			// set the clientId in a hidden field
			clientForm.find('#clientId').val(clientId);
			
			// extras
			var checkedExtras = $('input[name=extrasList]:checked');
			if (checkedExtras.length) {
				checkedExtras.each(function(index) {
					extras[index] = $(this).val();
					//console.log('index =',index,': val(id) = ',$(this).val());
				});
			}
			else {
			}
			
			// set transport options
			//transport = $('#transportOption').find('select').val();
			
			var dialogOpt = {
				width:		280,
				height:		200,
				show: 		'fade',
				hide: 		'fade',
				buttons: {
					"Ok": function() { // make reservation
						
						$.ajax({
							url:		window.ajaxUrl + '/createReservationAction',
							type:		'POST',		
							async:		true,		
							dataType:	"json",		
							data:
							{
								offer_id: 	offer_id,
								class_id: 	class_id,
								client_id: 	clientId,
								//transport: 	transport,
								extras: 	extras
							},
							success: function(data,textStatus,jqXHR) {
								
								// reservation was succefully created
								var alertDialog = $('#genericAlert');
								
								alertDialog.html(data.msg);
								
								alertDialog.dialog({
									width:		350,
									height:		150,
									show: 		'fade',
									hide: 		'fade',
									buttons: {
										"Ok": 		
										function() {
											window.location.href = window.ajaxUrl + '/reservations';
											$(this).dialog("close");
										}
									}
								});
							},
							error:		function(jqXHR, textStatus, errorThrown) {	
								
							},
							complete: function(xhr, status) {
								
							}
						});
						
						$(this).dialog("close");
					},
					"Cancelar": function() {
						$(this).dialog("close");
					}
				}
			};
			
			// build the dialog 
			$('#confirmation').dialog(dialogOpt);
			
			// get info about the client
			var clientInfo = {};
			jQuery.each(clientForm.serializeArray(), function(i, field) {
				clientInfo[field.name] = field.value;
			});
		}
		else { // ... no client selected
			showAlert('Qual o cliente?','selecione um cliente ...', 350, 150);
		}
}




/**
 * Remove all data from clientForm fields
 * Remove any message
 * set hidden attr 'clientId' to '0' and
 * update the label of the button to 'createClient'
 */
function clearClientForm() {
	
	var clientForm = $('#clientForm');
	
	// clear all 'input' fields inside clientForm
	clientForm.children().each(function(i,e) {
		
		var input = $(this).find('.controls input:text');
		
		if (input.length > 0) {
			
			$(this).attr('class','control-group')
				.find('input')
				.val('') .end()
				.find('.help-inline')
				.html('');
		}
	});
	
	// clear the textarea
	$('#clientInfo .controls textarea').val('');
	
	// reset the clientId
	clientForm.attr('data-id',0);
	
	// remove all 'error' 'success' messages
	$('#createClientAlert').removeClass('alert alert-error alert-success').html('');
	
	// update the button label
    $('#createButton').html('Criar Cliente');
}





/**
 * Function to update or create a client
 * @param values - values to send to the server
 * @param methodName - the name of the function to process the data
 */
function sendCltData2Srv(values, methodName) {
	
	$.ajax({
		url:		window.ajaxUrl + methodName, 
		type:		'POST',		// type of request to make
		async:		true,		// asynchronous/synchronous request
		dataType:	"json",		// type of data returned from server
		
		data: values,
		
		success: 	function(data, textStatus, jqXHR) {
			
			var createClientAlert = $('#createClientAlert');
			
			if (data.Result) {
				
				createClientAlert.removeClass('alert alert-error').addClass('alert alert-success').html(data.msg);
				
				setTimeout(function() {
					createClientAlert.removeClass('alert alert-error alert-success').html('');
				}, 2000);
				
				clearClientForm();
				//$('#createButton').html('Actualizar'); 
				//$('#clientForm').attr('data-id',clientData.id);
			}
			else {
				createClientAlert.removeClass('alert alert-success')
					.addClass('alert alert-error')
					.html(data.msg);
			}
			
			// reload datatable client data from server
			$('#clientTable').dataTable().fnReloadAjax();
		},

		// something went wrong ...
		error:		function(jqXHR, textStatus, errorThrown) {	
		},
		
		// code to run regardless of success or failure
		complete: function(xhr, status) {
		}
	});
}



/**
 * load and create the list with available extras 
 */
function loadExtras() {
	
	// hold available extras to add to the selected offer
	var data = {};
	
	// get the selected offer
	var defaultCheckedOffer = $('input[name=offerRadio]:checked');
	
	var transportOption = $('#transportOption');
	transportOption.empty();
	
	// if there is no available offers (jquery obj is empty)
	if (!defaultCheckedOffer.length) {
		transportOption.html('<p> ... não existem ofertas, logo nao existem extras associados.');
		return;
	}
	
	// add first the dropdown to choose the transport option
	//var transportLabel = ' <label>Transporte:</label> <select> <option value="yes">sim</option> <option value="no">não</option> </select>';
	//$(transportLabel).appendTo(transportOption);
	
	// grab the offerId from the selected row and retrieve the available extras to include in the offer
	link = defaultCheckedOffer.parents().eq(1).find('a');
	data.offer_id = link.attr('data-offerId');
	var extrasData = getDataFromSrv(data, '/getExtras2Include');
	
	// the element where the extras will be placed
	var extrasList = $('#extrasList');
	
	extrasList.empty();
	
	var extraElements = '<label class="control-label">Extras:</label>';
	
	$(extraElements).appendTo(extrasList);
	
	// create the list of checkbox extra 
	jQuery.each(extrasData, function(index,value) {
		extraElements = '<label class="checkbox"> <input type="checkbox" data-price="' + value.price +'" value="' + value.id + '" name="extrasList">' + value.name + ' (' + value.price + ' €)</label>';
		$(extraElements).appendTo(extrasList);
	});
	
	var price = link.attr('data-price');
	$('#totalCost').val(price).html(price + '€');
}


/**
 * handle events from the offer list
 */
function offerListEvents() {
	
	
	// selected offer
	var defaultCheckedOffer = $('input[name=offerRadio]:checked');
	
	var price = 0;
	
	// price associated to the offer
	if (defaultCheckedOffer.length) 
		price = defaultCheckedOffer.parents().eq(1).find('a').attr('data-price');
	
	// when the user click the link with the name of the offer
	$('.offerName').click(function(event) {
		
		event.preventDefault();
		
		var data = {};

		console.log($(this));

		data.offerId = $(this).attr('data-offerId');
		data.userId = $(this).attr('data-userId');
		data.classId = $(this).attr('data-classid');
		
		offerData = getDataFromSrv(data, "/getOfferInfo");
		//console.log('offerData = ',offerData[0]);
		
		// show pop up
		var offerInfoDialog = $('#offerInfoDialog');
		offerInfoDialog.attr('title','title');
		offerInfoDialog.find('.price p').text(offerData[0].price);
		offerInfoDialog.find('.level p').text(offerData[0].level);
		offerInfoDialog.find('.description p').text(offerData[0].description);
		
		var properties = {
			width:		500,
			height:		400,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				}
			}
		};
		
		offerInfoDialog.dialog(properties); 
	});

	// when user click the link with the number of available classes 
	$('.classes').click(function(event) {
		
		event.preventDefault();
		
		var data = {};

		console.log($(this));
		
		// retrieve schedule info from the given offer
		data.offerId = $(this).attr('data-offerId');
		data.classId = $(this).attr('data-classId');
		//data.userId = $(this).attr('data-userId');
		scheduleData = getDataFromSrv(data, "/getScheduleInfo"); 
		
		console.info('data to show in calendar', scheduleData);
		//return;
		
		var popUpCalendarDialog = $('#popUpCalendarDialog');
		
		// clear the previous content
		popUpCalendarDialog.empty();
		
		$.each(scheduleData, function(key,value){
			var cal_container = '<div class="cal-container"><div class="cal-class-label inside-cal-container">' + '<p>Aula '+ (key + 1) + ':</p></div> <div class="cal-data-container inside-cal-container"><div class="cal-date-label"><p>Inicio:</p></div><div class="cal-date"><p>' + scheduleData[key].start +'</p></div><div class="cal-date-label"><p>Fim:</p></div><div class="cal-date"><p>' + scheduleData[key].end + '</div></p></div></div>'; 
			$(cal_container).appendTo(popUpCalendarDialog);
		});
		
		/*
		for ( var i = 0; i < 3 ; i++) {
			var cal_container = '<div class="cal-container"><div class="cal-class-label inside-cal-container"><p>Aula '+ i + ':</p></div> <div class="cal-data-container inside-cal-container"><div class="cal-date-label"><p>Inicio:</p></div><div class="cal-date"><p>' + 'start' +'</p></div><div class="cal-date-label"><p>Fim:</p></div><div class="cal-date"><p>' + 'end' + '</div></p></div></div>';
			$(cal_container).appendTo(popUpCalendarDialog);
		}
		*/
		
		// console.log('data = ',data);
		
		// build pop up
		var properties = {
			width:		500,
			height:		400,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				}
			}
		};
		
		// show dialog
		popUpCalendarDialog.dialog(properties); 
	});
	
	// ... event when a new offer is selected
	$('input[name=offerRadio]').change(function() {
		
		// offer info that is going to be send to the server
		var data = {};
		var link = $(this).parents().eq(1).find('a');
		data.offer_id 	= link.attr('data-offerId');
		
		// add the price to the label
		var price = link.attr('data-price'); 
		//price = parseInt(price);
		$('#totalCost').val(price).html(price + '€');
		
		var extrasList = $('#extrasList');
		
		var extrasData = getDataFromSrv(data, '/getExtras2Include');
		
		var extraElements = '<label class="control-label">Extras:</label>';
		
		// no extras available
		if ( !extrasData ) {
			var element = '<p> não existem extras ...</p>';
			extrasList.empty();
			$(element).appendTo(extrasList);
			return;
		}
		
		extrasList.empty();
		
		$(extraElements).appendTo(extrasList);
		
		// create the list of checkbox extra 
		jQuery.each(extrasData, function(index,value) {
			//extraElements = '<label class="checkbox"> <input type="checkbox" value="' + value.id + '" name="extrasList">' + value.name + '</label>';
			extraElements = '<label class="checkbox"> <input type="checkbox" data-price="' + value.price +'" value="' + value.id + '" name="extrasList">' + value.name + ' (' + value.price + ' €)</label>';
			$(extraElements).appendTo(extrasList);
		});
		
		// associate an event to the new list of extras
		extrasListEvents();
	});
}



/**
 * handle events from the extras checkbox
 */
function extrasListEvents() {
	
	// ...
	$('input[name=extrasList]').change(function() {
		
		//console.log('price: ', $(this).attr('data-price'));
		
		//var price = $(this).attr('data-price');
		//console.log('$(this)', $(this));
		
		var total = 0;
		
		var checkedExtras = $('input[name=extrasList]:checked');
		//console.log('checkedExtras', checkedExtras);
		
		// iterate through the selected extras
		checkedExtras.each(function(index) {
			//console.log('price = ', $(this).attr('data-price'));
			total += parseInt($(this).attr('data-price'));
		});
		//jQuery.each(checkedExtras, function(index, value) {
			//total += value.attr('data-price');
			//console.log('value', value);
		//});
		
		// add the price of the selected offer
		var offerPrice = $('input[name=offerRadio]:checked').parents().eq(1).find('a').attr('data-price');
		offerPrice = parseInt(offerPrice);
		total += offerPrice;
		
		// show the final price
		//console.log('total', total);
		//var price = link.attr('data-price');
		$('#totalCost').val(total).html(total + ' €');
	});
}




/**
 * Validate client form fields on 'blur' event, and clear the data 'focus' event
 */
function formFocusEvents() {
	
	$('#clientForm').children().each(function(i,e) {
		
		// select the input text field 
		var input = $(this).find('.controls input:text');

		// if an input text field exists ...
		if (input.length > 0) {
			
			// add blur event to each input text field
			input.blur(function() {
				
				if ($(this).val() == '') {
					$(this).parents('.control-group')
						.addClass('error')
						.find('.help-inline')	
						.html('campo obrigatorio');
				}
				else {
					$(this).parents('.control-group')
						.addClass('success')
						.find('.help-inline')
						.html('');
				}
			});

			// add focus event to each input text field
			input.focus(function() {
				$(this).parents('.control-group')
					.removeClass('success error')
					.find('.help-inline')
					.html('');
			});
		}
		else { // ... it isnt an input text field
			
		}
	});
}


/**
 * clientForm first configurations 
 */
function formConf() {
	
	var clientBirthday = $("#clientBirthday").find('input');
	//console.log(clientBirthday);
	
	var conf = {
		showButtonPanel: 	true,
		changeMonth: 		true,
		changeYear: 		true,
		dateFormat: 		'yy-mm-dd',
		//dateFormat: 		'@',
		//showAnim:			'fade',
		defaultDate:		'1980-07-07',
		yearRange: 			'1920:2012',
		//currentText: 'Now'
		onSelect:			function() {
			$('#clientBirthday').addClass('success').find('.help-inline').html('');
		}
	};
	
	clientBirthday.datepicker(conf);
	
	
	// all checkboxes with the client spoken languages 
	var langInputs = $('#clientLanguages label input');
	
	// pt and en are check by default 
	langInputs.parent().find('input[value=pt],[value=en]').attr('checked','checked');
}




/**
 * validate form fields
 * @returns true if all forms are ok, false otherwise
 */
function validateForm() {
	
	var count = 0;
	
	var everythingOk = true; 
		
	$('#clientForm').children().each(function(i,e) {
		
		// select an input text field
		var input = $(this).find('.controls input:text');
		
		
		// if an input text field exists ...
		if ( input.length > 0 ) {
			
			count++;
			
			// empty field?
			if (input.val() == null || input.val() == '') {
				
				$(this) .addClass('error')
					.find('.help-inline')
					.html('campo obrigatorio');
				
				everythingOk = false;
				
				var createClientAlert = $('#createClientAlert');
		
				createClientAlert.removeClass('alert alert-error alert-success')
					.addClass('alert alert-error')
					.html('existem campos nao preenchidos');
			}
			
			// ... add other restrictions here
		}
			
	});
	
	return everythingOk;
}




/**
 * this function adds the plugin 'fnReloadAjax' to the datatable prototype so we can reload 
 * data from server and use the local search feacture (avoiding this way the use of the server by the search field)
 */
function datatablePlugins() {
	
	// fnReloadAjax
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
	{
	    if ( typeof sNewSource != 'undefined' && sNewSource != null )
	    {
	        oSettings.sAjaxSource = sNewSource;
	    }
	    this.oApi._fnProcessingDisplay( oSettings, true );
	    var that = this;
	    var iStart = oSettings._iDisplayStart;
	    var aData = [];
	 
	    this.oApi._fnServerParams( oSettings, aData );
	     
	    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
	        /* Clear the old information from the table */
	        that.oApi._fnClearTable( oSettings );
	         
	        /* Got the data - add it to the table */
	        var aData =  (oSettings.sAjaxDataProp !== "") ?
	            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
	         
	        for ( var i=0 ; i<aData.length ; i++ )
	        {
	            that.oApi._fnAddData( oSettings, aData[i] );
	        }
	         
	        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	        that.fnDraw();
	         
	        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
	        {
	            oSettings._iDisplayStart = iStart;
	            that.fnDraw( false );
	        }
	         
	        that.oApi._fnProcessingDisplay( oSettings, false );
	         
	        /* Callback user function - for event handlers etc */
	        if ( typeof fnCallback == 'function' && fnCallback != null )
	        {
	            fnCallback( oSettings );
	        }
	    }, oSettings );
	};
}






/**
 * initialize datatable plugin
 */
function datatableClient() {
	
	var clientTable = $('#clientTable');
	
	var clientForm 	= $('#clientForm');
	
	var createButton = $('#createButton');
	
	// data retrieved from the datatable
	var clientData = null;
	
	// clientId=0 means no client data is in the form
	clientForm.attr('data-id',0);
		
	// feed the datatable from this link
	var serverRequest = window.ajaxUrl + '/getClients';

	// datatable options 
	var tableProperties = {
		'sDom':				"<'row'<'span8'l><'span4'f>r>t<'row'<'span8'i><'span4'p>>", // bootstrap integration
		'sAjaxSource': 		serverRequest,	
		'sServerMethod':	'POST',
		'sAjaxDataProp': 	'data',
		'fnServerParams': 	function (aoData) {
				aoData.push( {'var1':'value1','var2':'value2'});
		},
		"aoColumns": [
			{"mDataProp":"name"},
			{"mDataProp":"address"},
			{"mDataProp":"email"},
			{"mDataProp":"phone"},
			{"mDataProp":"birthday"}
		],
		'aaSorting':[[4,'desc']],	// or 'asc'
		'bJQueryUI':		false,	// enable jqueryUI Themes
		'bPaginate':		true,
		'bSort':			true,
		'bInfo':			true,
		'bAutoWidth':		true,
		'bProcessing': 		true,
		'bServerSide': 		false,	// use server side processing
		'oLanguage': {
			'sInfo':		'registos _START_ até ao _END_ de _TOTAL_',
			'sZeroRecords': 'Não existem clientes',
			'sSearch':		'Procurar',
			'sLengthMenu':	'Mostrar <select>' +
				'<option value="5">5</option>'+
				'<option value="10">10</option>'+
		        '<option value="20">20</option>'+
		        '<option value="30">30</option>'+
		        '<option value="40">40</option>'+
		        '<option value="50">50</option>'+
		        '<option value="-1">Todos</option>'+
		        '</select> registos'
		}	
	};

	// set datatable options
	clientTable.dataTable(tableProperties);
	
	// CLICK EVENTS
	clientTable.find('tbody tr').live('click',function() {
		
		// get data from the selected row
		clientData = clientTable.fnGetData(this); 
		
		// break here if there is no client in the table
		if ( !clientData )
			return;
		
		if ( $(this).hasClass('row_selected') ) { // ... the row is already selected
			
            $(this).removeClass('row_selected'); 
            
            // reset clientForm
            clearClientForm();
		} 
		else { // ... no row selected
			
	        // avoid multi selected row ... 
           	clientTable.$('tr.row_selected').removeClass('row_selected');
           	
           	// highlight selected row
            $(this).addClass('row_selected');
            
            // change button label
           	createButton.html('Atualizar'); 
           	
            // set the client id
			clientForm.attr('data-id',clientData.id);
			
			// fill form with all client info
			clientForm.find('#clientName input').val(clientData.name).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientAddress input').val(clientData.address).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientEmail input').val(clientData.email).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientPhone input').val(clientData.phone).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientHeight input').val(clientData.height).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientBirthday input').val(clientData.birthday).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientWeight input').val(clientData.weight).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientSex select').val(clientData.sex);
			clientForm.find('#clientNationality input').val(clientData.nationality).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientInfo textarea').val(clientData.info);
		}
	});
}




/**
 * Handle button events here
 */
function buttonEvents() {
	
	// the form to create the client
	var clientForm = $('#clientForm');
	
	var clientTable = $('#clientTable');
	
	// buttons
	var createButton 	= $('#createButton');
	var reserveButton 	= $('#reserveButton');
	var refreshButton 	= $('#refreshButton');
	var deleteButton 	= $('#deleteButton');
	var clearButton 	= $('#clearButton');
	var tmpButton 		= $('#tmpButton');
	
	// BUTTON CREATE/UPDATE CLIENT
	createButton.click(function() {
		
		// client side data validation ...
		if (!validateForm()) {
			return;
		}
		
		// grab all values from clientForm with attr 'name' 
		var clientInfo = {};
		jQuery.each(clientForm.serializeArray(), function(i, field) {
			clientInfo[field.name] = field.value;
		});
		
		// set the ID
		clientInfo['clientId'] = clientForm.attr('data-id');
		
		// create or update client ?
		if ( clientInfo['clientId'] == 0 ) {
			sendCltData2Srv(clientInfo, '/createClientAction');
		}
		else {
			sendCltData2Srv(clientInfo, '/updateClientAction');
		}
	});
	
	// CLEAR BUTTON
	clearButton.click(function() {
		
		selected = $('#clientTable .row_selected');
		
		// remove the selection if there is one client selected in the table
		if (selected.length) 
			selected.removeClass('row_selected');
		
		clearClientForm();
	});
	
	// RESERVE BUTTON 
	reserveButton.click(function() {
		reserveButtonAction();
	});
	
	// REFRESH BUTTON
	refreshButton.click(function() {
		clientTable.dataTable().fnReloadAjax();
	});
	
	// DELETE BUTTON
	deleteButton.click(function() {
		
	});
	
	// TMP BUTTON
	tmpButton.click(function() {
		showAlert('title', 'content', 300, 200);
	});

}








